/**
 * Copyright (c) 2013 onionframework.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.onionframework.code.service;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;

import org.onionframework.code.model.Code;
import org.onionframework.code.model.CodeType;
import org.onionframework.persistence.dao.GenericDao;
import org.onionframework.persistence.query.OnionQuery;
import org.onionframework.persistence.service.GenericServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

/**
 * @author allan
 *
 */
@Service("code.codeService")
public class CodeService extends GenericServiceImpl<Code>{

	@Autowired @Qualifier("code.codeDao")
	private GenericDao<Code> codeDao;
	
	@PostConstruct
	public void init(){
		super.setDao(this.codeDao);
	}
	
	@Caching(
			evict={
				@CacheEvict(value="onion.code.codeValue",key="#code.type.id.concat('-').concat(#code.value)"),
				@CacheEvict(value="onion.code.codeList",key="#code.type.id")
			}
	)
	public void save(Code code){
		super.save(code);
	}
	
	@Cacheable(value="onion.code.codeList",key="#type.id")
	public List<Code> getCodeList(CodeType type){
		return this.find(OnionQuery.instance(Code.class)
				.eq("type", type).asc("index"));
	}
	
	@Cacheable(value="onion.code.codeValue",key="#type.id.concat('-').concat(#value)")
	public Code getCode(String value, CodeType type) {
		return this.findUnique(OnionQuery.instance(Code.class)
					.eq("type", type)
					.eq("value", value));
	}
	
	@Override
	@Caching(
			evict={
				@CacheEvict(value="onion.code.codeValue",key="#code.type.id.concat('-').concat(#code.value)"),
				@CacheEvict(value="onion.code.codeList",key="#code.type.id")
			}
	)
	public void remove(Code code){
		super.remove(code);
	}
	
	@Override
	public void removeById(Serializable id){
		throw new UnsupportedOperationException("不支持此操作");
	}
	
}
